<?php

class TopicController extends Controller {
	
	public $createTopicUrl;

	private $_model;
	
	public function accessRules() {
		return array(
			array('allow',
				'actions' => array('index', 'view', 'create', 'update', 'delete'),
				'users' => array('@'),
			),
			array('deny'),
		);
	}
	
	public function init(){
		parent::init();
		$this->createTopicUrl = $this->createUrl('create'); 
	}
	
	
	public function actionIndex() {
		$model = new Topic(Yii::app()->user->isAdmin? 'adminSearch':'userSearch');
	
		$this->render('index',array(
			'dataProvider'=>Yii::app()->user->isAdmin? $model->adminSearch():$model->userSearch(),
		));
	}
	
	public function actionView($id) {
		
		$model = $this->loadModel($id);
		
		$post = new Post(Yii::app()->user->isAdmin? 'adminCreate': 'userCreate');
		$post->autoFill();
		$post->topic_=$model->id;
		$this->performAjaxValidation($post);
		
		$params=Yii::app()->request->getParam(get_class($post));
		if ($params) {
			$post->attributes=$params;
			$post->image_= CUploadedFile::getInstances($post, 'image_');
			//$post->imageEditor_= ActiveForm::getFormInstance($form, 'imageEditor_');
			$post->validate();
		
			echo $post->hasErrors()?'yes':'no';
			
			if (!$post->hasErrors() && $post->addRecord()) {
				$model->updatePostCounter();
				$this->setFlash('success', Lang::t('news.create.flash.success'));
				//$this->redirect(array('update', 'id' => $post->id));
				$this->redirect(Yii::app()->request->urlReferrer);
			} else {
				$this->setFlash('error', Lang::t('news.create.flash.fail'));
				//if($this->debugMode) print_r($post->getErrors());
			}
		}
		
		$dataProvider = Yii::app()->user->isAdmin? $post->adminSearch($model->id): $post->userSearch($model->id);
		$this->render('view', array(
			'data' => $model,
			'post' => $post,
			'dataProvider'=>$dataProvider,
			'formConfig' => array(
				'id' => $this->formId,
				'enableAjaxValidation' => true,
				'enableClientValidation' => true,
				'clientOptions' => array(
						'validateOnSubmit' => true,
				),
				'htmlOptions' => array(
						'enctype' => 'multipart/form-data',
				),
				'focus' => array($post, 'title_'),
			),
		));			
	}
	
	public function actionCreate() {
		$model = new Topic('adminCreate');
		$model->autoFill();
		$content=new Content('adminCreate');
		$content->autoFill($model);
		$content->validatorList->add(CValidator::createValidator('required', $content, 'title_, description_'));
		
		$this->performAjaxValidation($model, $content);
		
		$params=Yii::app()->request->getParam(get_class($model));
		$contentParams=Yii::app()->request->getParam(get_class($content));
		if ($params && $contentParams) {
			$model->attributes=$params;
			$model->image_= CUploadedFile::getInstances($model, 'image_');
			//$model->imageEditor_= ActiveForm::getFormInstance($form, 'imageEditor_');
			$model->validate();
		
			$content->attributes=$contentParams;
			$content->validate();
		
			if (!$model->hasErrors() && !$content->hasErrors() && $model->addRecord($content)) {
				$this->setFlash('success', Lang::t('news.create.flash.success'));
				$this->redirect(array('update', 'id' => $model->id));
			} else {
				$this->setFlash('error', Lang::t('news.create.flash.fail'));
				//if($this->debugMode) print_r($model->getErrors());
			}
		}
		$this->render('createForm', array(
			'topic' => $model,
			'content'=>$content,
			'formConfig' => array(
					'id' => $this->formId,
					'enableAjaxValidation' => true,
					'enableClientValidation' => true,
					'clientOptions' => array(
							'validateOnSubmit' => true,
					),
					'htmlOptions' => array(
							'enctype' => 'multipart/form-data',
					),
					'focus' => array($content, 'title_'),
			),
		));
	}
	
	public function actionUpdate($id) {
		$model = $this->loadModel($id);
		$model->scenario = 'adminUpdate';
		$model->autoFill();
		$content=empty($model->html)?new Content('adminCreate'):$model->html;
		$content->autoFill($model);
		$content->validatorList->add(CValidator::createValidator('required', $content, 'title_, description_'));
		
		$this->performAjaxValidation($model, $content);
		
		$params=Yii::app()->request->getParam(get_class($model));
		$contentParams=Yii::app()->request->getParam(get_class($content));
		if ($params && $contentParams) {
			$model->attributes=$params;
			$model->image_= CUploadedFile::getInstances($model, 'image_');
			$model->validate();
			$content->attributes=$contentParams;
			$content->validate();
		
			if (!$model->hasErrors() && !$content->hasErrors() && $model->updateRecord($content)) {
				$model->refresh();
				$this->setFlash('success', Lang::t('news.update.flash.success'));
				$this->refresh();
			}else{
				$this->setFlash('error', Lang::t('news.update.flash.fail'));
				//if($this->debugMode) print_r($model->errors);
			}
		}
		$this->render('updateForm', array(
				'topic' => $model,
				'content'=>$content,
				'formConfig' => array(
					'id' => $this->formId,
					'enableAjaxValidation' => true,
					'enableClientValidation' => true,
					'clientOptions' => array(
							'validateOnSubmit' => true,
					),
					'htmlOptions' => array(
							'enctype' => 'multipart/form-data',
					),
					'focus' => array($content, 'title_'),
				),
		));
	}
	
	public function actionDelete($id) {
		$model=$this->loadModel($id);
		$model->scenario='adminDelete';
		if ($model->deleteRecord()) {
			$this->setFlash('success', Lang::t('news.delete.flash.success'));
		}else{
			$this->setFlash('error', Lang::t('news.delete.flash.fail'));
			//if($this->debugMode) print_r($model->errors);
		}
	
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		//if (!isset($_GET['ajax']))
		$this->redirect(Yii::app()->homeUrl);
	}

	public function loadModel($id) {
		if ($this->_model === null) {
			if (!empty($id))
				$this->_model = Topic::model()->accessible()->findByPk((int) $id);
	
			if ($this->_model === null)
				HttpStatus::code(404);
		}
		return $this->_model;
	}
}